
package com.lemon.ai.socket.packets.spiritgame.model.generator;
import static com.lemon.ai.socket.packets.spiritgame.model.generator.utils.StringUtils.*;
import java.util.List;
import java.util.Map.Entry;

import com.lemon.ai.socket.packets.spiritgame.model.db.MetaData;
import com.lemon.ai.socket.packets.spiritgame.model.dto.Column;
import com.lemon.ai.socket.packets.spiritgame.model.dto.Table;
import com.lemon.ai.socket.packets.spiritgame.model.generator.utils.StringParser;
import com.lemon.ai.socket.packets.spiritgame.model.generator.utils.StringUtils;

/**
 * dao接口生成器
 * @author dengzongrong
 * @version 1.1
 * @date 2011-10-09
 */
public class DaoIfcGenerator extends AbstractGenerator {

	public DaoIfcGenerator() {
		super("DaoIfcTemp.txt");
	}

	public String generate(Table table) {
		return super.temp.replace("PACKAGE_NAME",super.prop.getProperty("package")).
				replace("FINDERS", generateFinders(table)).
				replace("CLASS_NAME", generateClassName(table.getName())).
				replace("CLASS_PARAMETER", generateParameterName(table.getName())).
				replace("PK_PARAMETERS", StringParser.generatePkParameters(table));
	}

	/**
	 * 创建所有finder方法
	 * @param table
	 * @return
	 */
	private String generateFinders(Table table) {
		
		String temp = "public List<CLASS_NAME> findByMETHOD_NAME(COLUMN_TYPE o);";
		
		String[] finders = table.getFindByMethods();
		
		StringBuilder sb = new StringBuilder();
		
		for (String fs : finders) {
			Column c = table.getColumns(fs);
			if(fs.isEmpty()) 
				continue;
			sb.append(
					temp.replaceAll("METHOD_NAME", StringUtils.firstToUpperCase(c.getName())).
					replaceAll("COLUMN_TYPE", StringParser.updateTypeFromDb(c.getType()))
					);
			sb.append("\r");
		}
		sb.append("\r");
		for (Entry<String, List<Column>> e : table.getSameColumns().entrySet()) {
			sb.append( "\tpublic static final int " + e.getKey().toString().toUpperCase() + "_LEN = " + e.getValue().size() + ";\r");
		}
		return sb.toString();
	}

	public String generateFileName(Table table) {
		return super.prop.getProperty("dir")
				+ super.prop.getProperty("package").replace(".", "\\")
				+ "\\dao\\" + generateClassName(table.getName())
				+ "DAO.java";
	}

	public static void main(String[] args) {
		MetaData meta = MetaData.getInstance();
		List<Table> tables = meta.getTables();
		DaoIfcGenerator g = new DaoIfcGenerator();
		System.out.println(g.generate(tables.get(0)));
	}

}
